<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class Product extends Model implements Sortable
{
    use SortableTrait;

    public $sortable = [
        'order_column_name' => 'sort',
        'sort_when_creating' => true,
    ];

    protected $fillable = [
        'title',                #标题
        'shop_id',              #商店id
        'subtitle',             #副标题
        'image',                #主图
        'contact_phone',        #联系电话
        'content',              #内容(文)
        'pictures',             #内容(图)
        'service_time',         #服务时间
        'stock_amount',         #库存
        'view_amount',          #浏览量
        'sell_amount',          #成交量
        'sort',                 #排序
        'is_show',              #是否展示
        'province',             #省
        'city',                 #市
        'district',             #区
        'address',              #详细地址
        'longitude',            #经度
        'latitude',             #纬度
        'recommended',
    ];

    protected $casts = [
        'is_show' => 'boolean',
        'schedules' => 'json',
    ];

    static $IS_SHOW_MAP = [
        '否', '是',
    ];

    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id', 'id')->withDefault();
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'object');
    }

    public function order()
    {
        return $this->morphMany(Order::class, 'goods');
    }

    public function schedules()
    {
        return $this->morphMany(Schedule::class, 'goods')->orderBy('begin_time', 'asc');
    }

    public function setPicturesAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['pictures'] = implode(',', $pictures);
        } else {
            $this->attributes['pictures'] = $pictures;
        }
    }

    public function getPicturesAttribute($pictures)
    {
        if ($pictures) {
            return array_filter(explode(',', $pictures));
        }else{
            return [];
        }
    }
}
